package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Custromer;
import com.ruoyi.system.service.ICustromerService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-11-22
 */
@RestController
@RequestMapping("/system/custromer")
public class CustromerController extends BaseController
{
    @Autowired
    private ICustromerService custromerService;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:custromer:list')")
    @GetMapping("/list")
    public TableDataInfo list(Custromer custromer)
    {
        startPage();
        List<Custromer> list = custromerService.selectCustromerList(custromer);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:custromer:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Custromer custromer)
    {
        List<Custromer> list = custromerService.selectCustromerList(custromer);
        ExcelUtil<Custromer> util = new ExcelUtil<Custromer>(Custromer.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:custromer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(custromerService.selectCustromerById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:custromer:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Custromer custromer)
    {
        return toAjax(custromerService.insertCustromer(custromer));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:custromer:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Custromer custromer)
    {
        return toAjax(custromerService.updateCustromer(custromer));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:custromer:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(custromerService.deleteCustromerByIds(ids));
    }


    @PostMapping("/uploadExcel1")
    public AjaxResult uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 用于存储Excel数据
        Map<String, List<Map<String, Object>>> excelData = new HashMap<>();

        // 获取上传文件的原始名称
        String originalFilename = file.getOriginalFilename();

        // 检查文件类型是否为Excel
        if (originalFilename != null && (originalFilename.endsWith(".xlsx") || originalFilename.endsWith(".xls"))) {
            try (InputStream inputStream = file.getInputStream()) {
                // 去除文件后缀，作为Map的key
                String fileNameWithoutExtension = originalFilename.replaceFirst("\\.xlsx?$", "");
                ArrayList<Custromer> custromers = new ArrayList<>();
                // 调用自定义的processExcel方法处理Excel数据
                List<Map<String, Object>> sheetData = processExcel(inputStream);
                for (Map<String, Object> sheetDatum : sheetData) {
                    String code = (String) sheetDatum.get("hsdwdm");
                    String name = (String) sheetDatum.get("hsdwmc");
                    String id = UUID.randomUUID().toString();

                    Custromer custromer = new Custromer();
                    custromer.setId(id);
                    custromer.setCustomerCode(code);
                    custromer.setCustomerName(name);
                    custromers.add(custromer);
                    custromer.setIsFlag("未上传");
                    custromerService.insertCustromer(custromer);
                }
//                custromerService.saveOrUpdateBatch(custromers);
                // 将数据存入Map中
//                excelData.put(fileNameWithoutExtension, sheetData);
            } catch (Exception e) {
                System.err.println("Error processing Excel file: " + originalFilename + " - " + e.getMessage());
            }
        } else {
            throw new IllegalArgumentException("Uploaded file is not a valid Excel file.");
        }

        return AjaxResult.success("保存成功");
    }

    // 处理单个 Excel 文件
    private List<Map<String, Object>> processExcel(InputStream excelStream) throws IOException {
        List<Map<String, Object>> sheetData = new ArrayList<>();

        try (Workbook workbook = new XSSFWorkbook(excelStream)) {
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                if (sheet != null) {
                    processSheet(sheet, sheetData);
                }
            }
        }

        return sheetData;
    }

    // 解析一个 sheet
    private void processSheet(Sheet sheet, List<Map<String, Object>> sheetData) {
        Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            return;
        }

        int numColumns = headerRow.getPhysicalNumberOfCells();

        for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            Map<String, Object> rowData = new HashMap<>();

            for (int colIdx = 0; colIdx < numColumns; colIdx++) {
                Cell cell = row.getCell(colIdx);
                String columnName = headerRow.getCell(colIdx).getStringCellValue();
                Object cellValue = getCellValue(cell);
                rowData.put(columnName, cellValue);
            }

            sheetData.add(rowData);
        }
    }

    // 获取单元格内容
    private Object getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue();
                } else {
                    return cell.getNumericCellValue();
                }
            case BOOLEAN:
                return cell.getBooleanCellValue();
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
}
